﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ShowDBPool
{
    public class DBPool
    {
        private class SqlConnectionObject : IDynamicObject
        {
            private SqlConnection _SqlConn;

            public SqlConnectionObject()
            {
                _SqlConn = null;
            }

            #region IDynamicObject Members

            public void Create(Object param)
            {
                String strConn = (String)param;
                _SqlConn = new SqlConnection(strConn);
                _SqlConn.Open();
            }

            public Object GetInnerObject()
            {
                // TODO: Add SqlConnectionObject.GetInnerObject implementation
                return _SqlConn;
            }

            public bool IsValidate()
            {
                return (_SqlConn != null
                    && _SqlConn.GetHashCode() > 0
                    && _SqlConn.State == ConnectionState.Open);
            }

            public void Release()
            {
                // TODO: Add SqlConnectionObject.Release implementation
                _SqlConn.Close();
            }

            #endregion
        }

        private ObjectPool _Connections;

        public DBPool(string connection, int initcount, int capacity)
        {
            if (connection == null || connection == "" || initcount < 0 || capacity < 1)
            {
                throw (new Exception("Invalid parameter!"));
            }
            _Connections = new ObjectPool(typeof(SqlConnectionObject), connection, initcount, capacity);
        }

        public SqlConnection GetConnection()
        {
            return (SqlConnection)_Connections.GetOne();
        }

        public void FreeConnection(SqlConnection sqlConn)
        {
            _Connections.FreeObject(sqlConn);
        }

        public void Release()
        {
            _Connections.Release();
        }

        public int Count
        {
            get { return _Connections.CurrentSize; }
        }

        public int UsingCount
        {
            get { return _Connections.ActiveCount; }
        }

        public int DecreaseSize(int size)
        {
            return _Connections.DecreaseSize(size);
        }
    } // DBPool 

}
